package wdsys

import (
	"net"
	"strconv"
	"time"

	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/host"
	"github.com/shirou/gopsutil/load"
	"github.com/shirou/gopsutil/mem"
)

/*
	更多信息见包：  github.com/shirou/gopsutil
	参考信息见文章：https://www.liwenzhou.com/posts/Go/go_gopsutil
*/

//GetLocalIP ..获取本地ip地址
func GetLocalIP() string {
	conn, err := net.Dial("udp", "8.8.8.8:80")
	if err != nil {
		return ""
	}
	defer conn.Close()

	localAddr := conn.LocalAddr().(*net.UDPAddr)
	return localAddr.IP.String()
}

//GetCpuPercent 获取Cpu使用率,逻辑盒数，该函数至少需要一秒才能返回
func GetCpuPercent() (float64, int) {
	percent, _ := cpu.Percent(time.Second, false)
	couts, _ := cpu.Counts(true)
	return percent[0], couts
}

//GetCpuLoad 获取cpu负载，1 5 15分钟的负载
func GetCpuLoad(la int) float64 {
	info, _ := load.Avg()
	switch la {
	case 1:
		return info.Load1
	case 5:
		return info.Load5
	case 15:
		return info.Load15
	}
	return -1
}

//GetMemoryInfo ..获取内存使用情况 总数 空闲 使用 使用率
func GetMemoryInfo() (total, available, used uint64, percent float64) {
	memInfo, _ := mem.VirtualMemory()
	if memInfo != nil {
		total = memInfo.Total
		available = memInfo.Available
		used = memInfo.Used
		percent = memInfo.UsedPercent
	}
	return
}

//GetDiskInfo 获取分区信息  。。diskInfo, _ := disk.Usage(PartitionStat.Mountpoint) 获取使用情况
func GetDiskInfo() ([]disk.PartitionStat, error) {
	return disk.Partitions(true)
}

//GetHostInfo 获取系统信息
//0：主机名称 例--->WIN-DJ748UMR6RC
//1：运行时间
//2：开机时常
//3：运行系统 例--->windows
//4：虚拟总线 例--->Microsoft Windows 7 Ultimate Service Pack 1
//5：总线家族 例--->Standalone Workstation
//6：系统类型 例--->x86_64
//7：主机ID	 例--->16f1ce85-3f15-4f57-b3e9-9057b0666d5a
func GetHostInfo() (info []string) {
	hInfo, _ := host.Info()
	info = make([]string, 8)
	info[0] = hInfo.Hostname
	info[1] = strconv.Itoa(int(hInfo.Uptime))
	info[2] = strconv.Itoa(int(hInfo.BootTime))
	info[3] = hInfo.OS
	info[4] = hInfo.Platform
	info[5] = hInfo.PlatformFamily
	info[6] = hInfo.KernelArch
	info[7] = hInfo.HostID
	return
}
